package jdbc;

import java.sql.Connection;

import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.naming.Context;


public class ConnectionManager {
	private static final ConnectionManager instance = new ConnectionManager();
	private final DataSource dataSource;
	
	private final ThreadLocal<Connection> threadLocalConnections= new ThreadLocal<Connection>(){
		@Override
		protected Connection initialValue() {
			try{
				Connection c=dataSource.getConnection();
				c.setAutoCommit(false);
				return c;
			}
			catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	};
	
	private ConnectionManager(){
		try{
			InitialContext ic = new InitialContext();
	    	Context xmlContext = (Context) ic.lookup("java:/comp/env");
	        dataSource = (DataSource) xmlContext.lookup("jdbc/dataSource");
		}
		catch(NameNotFoundException nfe){
			throw new RuntimeException("Can't obtain dataSource from context. " +
                    "Have you added data source to context.xml file? " +
                    "Read javadoc on ConnectionManager.java file.");
		}
		catch(Exception e){
			throw new RuntimeException("Can't obtain dataSource from context", e);
		}
	}
	
	public Connection currentConnection(){
		return threadLocalConnections.get();
	}
	
	public static ConnectionManager getInstance(){
		return instance;
	}
	
	public void commitTransaction(){
		try{
			Connection c=currentConnection();
			c.commit();
			c.close();
			threadLocalConnections.remove();
		}
		catch (Exception e){
    		throw new RuntimeException(e);
    	}
	}
	
	public void rollbackTransaction(){
		try{
			Connection c=currentConnection();
			c.rollback();
			c.close();
			threadLocalConnections.remove();
		}
		catch (Exception e){
    		throw new RuntimeException(e);
    	}
	}

}
